﻿using FileWatcher;
using System.Reflection;
using WYJ.SDK.Core;

internal class Handler
{
    private static Dictionary<string, Action<string[]>> MethodDic { get; set; }

    public static void Invoke(string methodName, params string[] args)
    {
        if(methodName.StartsWith("-"))
        {
            if (App.Setting.CommandMap.ContainsKey(methodName)) methodName = App.Setting.CommandMap[methodName];
            else methodName = App.Setting.DefaultCommand;
        }
        if (!MethodDic.TryGetValue(methodName.ToLower(), out var method))
        {
            method = MethodDic[App.Setting.DefaultCommand];
        }
        method(args);
    }

    static Handler()
    {
        ReLoad();
    }

    [Tag]
    private static void Watch(string[] args)
    {
        var watcher =  new FileSystemWatcher(App.Setting.WorkingDirectory)
        {
            NotifyFilter =  NotifyFilters.DirectoryName
                    | NotifyFilters.FileName
                    | NotifyFilters.LastWrite
        };
        watcher.Changed += (object sender, FileSystemEventArgs e) =>
        {
            if (e.Log("Changed")) return;
            CopyFile(e.FullPath);
        };
        watcher.Created += (object sender, FileSystemEventArgs e) =>
        {
            if (e.Log("Created")) return;
            CopyFile(e.FullPath);
        };
        watcher.Deleted += (object sender, FileSystemEventArgs e) =>
        {
            e.Log("Deleted");
            DeleteFrom(e.FullPath);
        };
        watcher.Renamed += (object sender, RenamedEventArgs e) =>
        {
            e.Log("Renamed");
            Rename(e.OldFullPath, e.FullPath);
        };
        watcher.Error += (object sender, ErrorEventArgs e) =>
        {
            WYJConsole.PrintException(e.GetException());
            Environment.Exit(129);
        };
        watcher.IncludeSubdirectories = true;
        watcher.EnableRaisingEvents = true;
        Console.WriteLine($"开始监视 {watcher.Path}: {watcher.Filter}");
        WYJConsole.Ask("请按 X 键退出");
    }

    private static void Rename(string oldFullPath, string fullPath)
    {
        Directory.Move(oldFullPath.Replace(App.Setting.SrcDirectory, App.Setting.SyncDirectory), fullPath.Replace(App.Setting.SrcDirectory, App.Setting.SyncDirectory));
    }

    private static void DeleteFrom(string fullPath)
    {
        File.Delete(fullPath.Replace(App.Setting.SrcDirectory, App.Setting.SyncDirectory));
    }

    private static void CopyFile(string fullPath)
    {
        if (fullPath.EndsWith(".ts"))
        {
            return;
        }
            File.Copy(fullPath, fullPath.Replace(App.Setting.SrcDirectory, App.Setting.SyncDirectory),true);
        //await Task.Run(() =>
        //{
        //});
    }

    private static void ReLoad()
    {
        var ms = typeof(Handler).GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
        MethodDic = ms.Where(m=>m.GetCustomAttribute<Tag>() != null).ToDictionary(m => m.Name.ToLower(), m => m.CreateDelegate<Action<string[]>>());
    }

    [Tag]
    private static void Help(string[]? a)
    {
        string text = File.ReadAllText($"{App.ApplicationBase}/语法.txt");
        Console.WriteLine(text);
    }

    [Tag]
    private static void Version(string[]? a)
    {
        Console.WriteLine(App.Setting.Version);
    }

}
